package com.cskaoyan.market.filter;

import com.cskaoyan.market.config.WhiteListConfig;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @Author 鲸落
 * @Date 2024/5/8 9:41
 * @Version 1.0
 */
@Component
@Order(3)
public class AuthFilter extends OncePerRequestFilter {
    @Autowired
    WhiteListConfig whiteList;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        String method = request.getMethod();
        //通过打印日志我们可以发现，每次OPTIONS请求时，由于不会携带Cookie，都会创建一个新的session对象
        //虽然对于我们业务没有影响，但是每次请求都创建session对象，着实有一些浪费资源，所以options请求时直接忽略
        if(!"OPTIONS".equals(method)){
            HttpSession session = request.getSession();
            //获取请求资源
            String requestURI = request.getRequestURI();
            System.out.println(method + " " + requestURI + " " + session.getId() + " " + session);
            //
            //从配置文件中直接获取
            List<String> whiteUris = whiteList.getWhitelist();
//            ServletContext servletContext = request.getServletContext();
//            List<String> whiteUris = (List<String>) servletContext.getAttribute("white");
//            /admin/auth/login-------/app/admin/auth/login
            //希望可以直接使用list.contains方法，但是因为requesturi里面包含应用名，所以需要把应用名去掉
            requestURI = requestURI.replace(request.getContextPath(), "");
            if(!whiteUris.contains(requestURI)){
//            if(!requestURI.contains("/admin/auth/login") && !requestURI.contains("/admin/auth/logout")){
                //既不是登录也不是注销------进行认证，也就是需要登录之后才可以访问
                Object attribute = session.getAttribute("admin");
                if(attribute == null){
                    //没有登录 todo 返回结果未更改
                    response.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.unlogin()));
                    return;
                }
            }
        }
        //放行
        filterChain.doFilter(request, response);
    }
}
